local extension = Package:new("sifu_heg_kuo")
extension.extensionName = "sifu_heg"
local H = require "packages/ol_hegemony/util"
local U = require "packages/utility/utility"
local S = require "packages/sifu_heg/SeaFunc"
extension.game_modes_whitelist = {"zhonger_heg_mode"}

Fk:loadTranslationTable{
  ["sifu_heg_kuo"] = "国战SP武将",
  ["SP_heg"] = "国战SP"
}
-- 立状
--- 对某角色立状（抽取、选择、询问）
---@param from ServerPlayer @ 军令发起者
---@param to ServerPlayer @ 军令执行者
---@param skill_name string @ 技能名
---@param forced? boolean @ 是否强制执行
---@return boolean @ 是否执行
H.lizhuang = function(from, to, skill_name)
  if from.dead or to.dead then return false end
  local room = from.room
  room:sendLog{
    type = "#lizhuang",
    from = from.id,
    to = {to.id},
    arg = skill_name,
    toast = true,
  }
  --[[ -- 酷炫顶栏
  local ret = "<b><font color='#0C8F0C'>" .. Fk:translate(from.general)
  if from.deputyGeneral and from.deputyGeneral ~= "" then
    ret = ret .. "/" .. Fk:translate(from.deputyGeneral)
  end
  ret = ret .. "</b></font> " .. Fk:translate("to") .. " <b><font color='#CC3131'>" .. Fk:translate(to.general)
  if to.deputyGeneral and to.deputyGeneral ~= "" then
    ret = ret .. "/" .. Fk:translate(to.deputyGeneral)
  end
  ret = ret .. "</b></font> " .. " <b>" .. Fk:translate("start_command") .. "</b>"
  room:doBroadcastNotify("ServerMessage", ret)
  --]]
  local index = H.startLizhuang(from, skill_name)
  local invoke = H.doLizhuang(to, skill_name, index, from, forced)
  return invoke
end

--- 军令发起者抽取并选择军令
---@param from ServerPlayer @ 军令发起者
---@param skill_name string @ 技能名
---@return integer @ 选择的军令序号
H.startLizhuang = function(from, skill_name)
  local allcommands = {"command1", "command2", "command3", "command4", "command5", "command6"}
  local commands = table.random(allcommands, 1) ---@type string[]
  local room = from.room
  local choice = room:askForChoice(from, commands, "start_command", nil, true)
  room:sendLog{
    type = "#CommandChoice",
    from = from.id,
    arg = ":"+choice,
    toast = true,
  }
  --[[ -- 酷炫顶栏
  local ret = "<b><font color='#0C8F0C'>" .. Fk:translate(from.general)
  if from.deputyGeneral and from.deputyGeneral ~= "" then
    ret = ret .. "/" .. Fk:translate(from.deputyGeneral)
  end
  ret = ret .. "</b></font> " .. Fk:translate("chose") .. " <b>" .. Fk:translate(":"+choice) .. "</b>"
  room:doBroadcastNotify("ServerMessage", ret)
  --]]

  return table.indexOf(allcommands, choice)
end

--- 询问军令执行者是否执行军令（执行效果也在这里）
---@param to ServerPlayer @ 军令执行者
---@param skill_name string @ 技能名
---@param index integer @ 军令序数
---@param from ServerPlayer @ 军令发起者
---@param forced? boolean @ 是否强制执行
---@return boolean @ 是否执行
H.doLizhuang = function(to, skill_name, index, from, forced)
  if to.dead or from.dead then return false end
  local room = to.room
  local allcommands = {"command1", "command2", "command3", "command4", "command5", "command6"}
  local choice
  if 1 == 1 then
    choice = room:askForChoice(to, {allcommands[index]}, "do_command", nil, true, {allcommands[index], "Cancel"})
  end
  local result = choice == "Cancel" and "#commandselect_no" or "#commandselect_yes"
  room:sendLog{
    type = "#CommandChoice",
    from = to.id,
    arg = result,
    toast = true,
  }
  --[[ -- 酷炫顶栏
  local ret = "<b><font color='#CC3131'>" .. Fk:translate(to.general)
  if to.deputyGeneral and to.deputyGeneral ~= "" then
    ret = ret .. "/" .. Fk:translate(to.deputyGeneral)
  end
  ret = ret .. "</b></font> " .. Fk:translate("chose") .. " <b>" .. Fk:translate(result) .. "</b>"
  room:doBroadcastNotify("ServerMessage", ret)
  --]]
  if choice == "Cancel" then return false end
  local commandData = {
    from = from,
    to = to,
    command = index,
  }
  if room.logic:trigger("fk.ChoosedoLizhuang", to, commandData) then
    room.logic:trigger("fk.AfterCommandUse", to, commandData)
    return true
  end
  if index == 1 then
    local dest = room:askForChoosePlayers(from, table.map(room.alive_players, Util.IdMapper), 1, 1, "#command1-damage::" .. to.id, skill_name)[1]
    room:sendLog{
      type = "#Command1Damage",
      from = from.id,
      to = {dest},
    }
    room:doIndicate(from.id, {dest})
    room:damage{
      from = to,
      to = room:getPlayerById(dest),
      damage = 1,
      skillName = "command",
    }
  elseif index == 2 then
    to:drawCards(1, "command")
    if to == from or to:isNude() then return true end
    local cards = {}
    if #to:getCardIds{Player.Hand, Player.Equip} == 1 then
      cards = to:getCardIds{Player.Hand, Player.Equip}
    else
      cards = room:askForCard(to, 2, 2, true, "command", false, nil, "#command2-give::" .. from.id)
    end
    room:moveCardTo(cards, Player.Hand, from, fk.ReasonGive, "command", nil, false, from.id)
  elseif index == 3 then
    room:loseHp(to, 1, "command")
  elseif index == 4 then
    room:setPlayerMark(to, "@@command4_effect-turn", 1)
    room:addPlayerMark(to, MarkEnum.UncompulsoryInvalidity .. "-turn")
    room:handleAddLoseSkills(to, "#command4_prohibit", nil, false, true) --为了不全局，流汗了
  elseif index == 5 then
    to:turnOver()
    room:setPlayerMark(to, "@@command5_effect-turn", 1)
    room:handleAddLoseSkills(to, "#command5_cannotrecover", nil, false, true) --为了不全局，流汗了
  elseif index == 6 then
    if to:getHandcardNum() < 2 and #to:getCardIds(Player.Equip) < 2 then return true end
    local to_remain = {}
    if not to:isKongcheng() then
      table.insert(to_remain, to:getCardIds(Player.Hand)[1])
    end
    if #to:getCardIds(Player.Equip) > 0 then
      table.insert(to_remain, to:getCardIds(Player.Equip)[1])
    end
    local _, ret = room:askForUseActiveSkill(to, "#command6_select", "#command6-select", false)
    if ret then
      to_remain = ret.cards
    end
    local cards = table.filter(to:getCardIds{Player.Hand, Player.Equip}, function (id)
      return not (table.contains(to_remain, id) or to:prohibitDiscard(Fk:getCardById(id)))
    end)
    if #cards > 0 then
      room:throwCard(cards, "command", to)
    end
  end
  room.logic:trigger("fk.AfterCommandUse", to, commandData)
  return true
end

Fk:loadTranslationTable{
  ["command"] = "军令",
  ["#startLizhuang"] = "%arg：请选择一项军令<br>%arg2；<br>%arg3",
  ["command1"] = "军令一",
  ["command2"] = "军令二",
  ["command3"] = "军令三",
  ["command4"] = "军令四",
  ["command5"] = "军令五",
  ["command6"] = "军令六",
  [":command1"] = "军令一：对发起者指定的角色造成1点伤害",
  [":command2"] = "军令二：摸一张牌，然后交给发起者两张牌",
  [":command3"] = "军令三：失去1点体力",
  [":command4"] = "军令四：本回合不能使用或打出手牌且所有非锁定技失效",
  [":command5"] = "军令五：叠置，本回合不能回复体力",
  [":command6"] = "军令六：选择一张手牌和一张装备区里的牌，弃置其余的牌",
  ["start_command"] = "发起军令",
  ["#lizhuang"] = "%from 发动了 “%arg”，对 %to 发起了 <font color='#0598BC'><b>军令",
  ["#CommandChoice"] = "%from 选择了 %arg",
  ["chose"] = "选择了",
  ["do_command"] = "执行军令",
  ["#commandselect_yes"] = "执行军令",
  ["#commandselect_no"] = "不执行军令",
  ["#command1-damage"] = "军令：请选择 %dest 伤害的目标",
  ["#Command1Damage"] = "%from 选择对 %to 造成伤害",
  ["#command2-give"] = "军令：请选择两张牌交给 %dest",
  ["@@command4_effect-turn"] = "军令禁出牌技能",
  ["@@command5_effect-turn"] = "军令 不能回血",
  ["#command6-select"] = "军令：请选择要保留的一张手牌和一张装备",
}

local caorui = General(extension, "SP_heg__caorui", "wei", 3, 3, General.Male)
local cuzhan = fk.CreateTriggerSkill{
  name = "hurryfight",
  events = {fk.EventPhaseStart},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and target ~= player and target.phase == Player.Play and #player:getCardIds("he") > 1) then return false end
    return true
  end,
  on_cost = function (self, event, target, player, data)
    local cards = player.room:askForCard(player, 1, 1, true, self.name, true, ".", "#hurryfight-give")
    if #cards == 1 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:obtainCard(target, self.cost_data, false, fk.ReasonGive)
    if not target.dead then
      room:setPlayerMark(target, "@@hurryfight-turn", 1)
      room:setPlayerMark(target, "@@fight-turn", 1)
    end
  end
}
local fight_targetmod = fk.CreateTargetModSkill{
  name = "#fight_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:getMark("@@fight-turn") > 0 and scope == Player.HistoryPhase then
      return player:getMark("@@fight-turn")
    end
  end,
}
local cuzhan_delay = fk.CreateTriggerSkill{
  name = "#hurryfight_delay",
  events = {fk.EventPhaseEnd},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not (target:getMark("@@hurryfight-turn") > 0 and target.phase == Player.Play and player:usedSkillTimes(cuzhan.name, Player.HistoryTurn) > 0 and player:isAlive()) then return false end
    return #player.room.logic:getActualDamageEvents(1, function(e)
      return e.data[1].from == target
    end, Player.HistoryPhase) == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if H.lizhuang(player, target, self.name) then
    else
      return false
    end
  end,
}
local tingsong = fk.CreateTriggerSkill{
  name = "hearlawsuit",
  events = {fk.DamageCaused},
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    return target and H.compareKingdomWith(player, target) and player:hasSkill(self) and
      data.to:isAlive() and H.isSmallKingdomPlayer(data.to) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    data.damage = 0
    local targets = {}
    local num = 999
    for _, p in ipairs(room.alive_players) do
      local n = p.hp
      if n <= num then
        if n < num then
          num = n
          targets = {}
        end
        if n < p.maxHp then
          table.insert(targets, p.id)
        end
      end
    end
    if #targets > 0 then
      local to_heal = room:askForChoosePlayers(player, targets, 1, 1, "#hearlawsuit-choose", self.name, true)
      if #to_heal > 0 then
        room:recover{
          who = room:getPlayerById(to_heal[1]),
          num = 1,
          recoverBy = player,
          skillName = self.name,
        }
      end
    end
    return true
  end,
}
caorui:addSkill(cuzhan)
cuzhan:addRelatedSkill(fight_targetmod)
cuzhan:addRelatedSkill(cuzhan_delay)
caorui:addSkill(tingsong)
Fk:loadTranslationTable{
  ["SP_heg__caorui"] = "曹叡",
  ["#SP_heg__caorui"] = "幽梦魏祚明",
  ["illustrator:SP_heg__caorui"] = "Thinking",
  ["designer:SP_heg__caorui"] = "陌小奈",
  ["hurryfight"] = "促战",
  [":hurryfight"] = "其他角色的出牌阶段开始时，你可以交给其一张牌，令其此阶段可多使用一张【杀】，且其立状：此阶段结束时，其于此阶段造成过伤害。<br>\
  <font color='red'>立状：若立状的角色于对应的时机未完成立状的任务，其必须执行一个随机军令。</font>",
  ["hearlawsuit"] = "听讼",
  [":hearlawsuit"] = "每回合限一次，与你势力相同的角色对小势力角色造成伤害时，你可以防止此伤害，然后你可令一名体力值最小的角色回复1点体力。",
  ["@@hurryfight-turn"] = "促战",
  ["@@fight-turn"] = "可多使用一张【杀】",
  ["#hurryfight_delay"] = "促战",
  ["#hurryfight-give"] = "促战：你可交给其一张牌",
  ["#hearlawsuit-ask"] = "听讼：你可选择一名角色，防止此伤害并令一名体力值最小的角色回复1点体力",
  ["#hearlawsuit-choose"] = "听讼：你可令一名体力值最小的角色回复1点体力",
  ["$hurryfight1"] = "今贼兵入寇中原，卿安然坐视乎？",
  ["$hurryfight2"] = "大魏的未来，托付给爱卿了！",
  ["$hearlawsuit1"] = "百姓若得人间之福，朕何辞地狱之苦。",
  ["$hearlawsuit2"] = "弘法明理,不负众民之望。",
  ["~SP_heg__caorui"] = "悔不该耽于逸乐，至有今日。",
}

local wenyang = General(extension, "SP_heg__wenyang", "wei", 4)
wenyang:addCompanions("ze_heg__wenqin")
Fk:loadTranslationTable{
  ["SP_heg__wenyang"] = "文鸯",
  ["#SP_heg__wenyang"] = "独骑破军",
  ["illustrator:SP_heg__wenyang"] = "鬼画府",
  ["~SP_heg__wenyang"] = "半生功业，而见疑于一家之言，岂能无怨！",
}
local spquedi = fk.CreateViewAsSkill{
  name = "spquedi",
  anim_type = "offensive",
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 1
  end,
  card_filter = function()
    return false
  end,
  view_as = function(self, cards)
    local card = Fk:cloneCard("duel")
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player)
    player.room:askForDiscard(player, 1, 1, false, self.name, true, "slash", "请选择一张【杀】", true)
  end
}
Fk:loadTranslationTable{
  ["spquedi"] = "却敌",
  ["#spquedi_defence"] = "却敌",
  [":spquedi"] = "出牌阶段限一次，若你有【杀】，你可以视为使用一张【决斗】。",
  ["$spquedi1"] = "力摧敌阵，如视天光破云！",
  ["$spquedi2"] = "让尔等有命追，无命回！",
}
local spChoujue = fk.CreateTriggerSkill{
  name = "sp__choujue",
  anim_type = "drawcard",
  events = {fk.Deathed},
  frequency = Skill.Limited,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.damage and data.damage.from == player and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:drawCards(player, 3, self.name)
    room:recover({
      who = player,
      num = 1,
      recoverBy = player,
      skillName = self.name,
    })
  end,
}
Fk:loadTranslationTable{
  ["sp__choujue"] = "仇决",
  [":sp__choujue"] = "限定技，当你杀死一名角色后，你摸三张牌并回复1点体力。",
  ["$sp__choujue1"] = "血海深仇，便在今日来报！",
  ["$sp__choujue2"] = "取汝之头，以祭先父！",
}
wenyang:addSkill(spquedi)
wenyang:addSkill(spChoujue)

local caomao = General(extension, "SP_heg__caomao", "wei", 3)
local caomao2 = General(extension, "SP_heg__caomao2", "wei", 3)
caomao2.total_hidden = true
Fk:loadTranslationTable{
  ["SP_heg__caomao"] = "曹髦",
  ["#SP_heg__caomao"] = "向死存魏",
  ["~SP_heg__caomao"] = "纵不成身死，朕亦为太祖子孙，大魏君王……",
  ["SP_heg__caomao2"] = "曹髦",
}

local qianlong = fk.CreateTriggerSkill{
  name = "sp__qianlong",
  anim_type = "support",
  events = {fk.Damaged, fk.Damage, fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or player:getMark("@sp__qianlong_daoxin") > 98 then
      return false
    end

    if event == fk.AfterCardsMove then
      return table.find(data, function(move) return move.to == player.id and move.toArea == Card.PlayerHand end)
    elseif event == fk.Damaged or event == fk.Damage then
      return target == player
    end

    return event == fk.GeneralRevealed
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local num = 0
    if event == fk.Damage then
      num = 15 * data.damage
    elseif event == fk.Damaged then
      num = 20 * data.damage
    else
      num = 5
    end

    local daoxin = player:getMark("@sp__qianlong_daoxin")
    num = math.min(99 - daoxin, num)
    if num > 0 then
      room:setPlayerMark(player, "@sp__qianlong_daoxin", daoxin + num)
      if player:getMark("@sp__qianlong_daoxin") >= 25 and not player:hasSkill("sp_qianlong__qingzheng") then
        room:handleAddLoseSkills(player, "sp_qianlong__qingzheng")
      end
      if player:getMark("@sp__qianlong_daoxin") >= 50 and not player:hasSkill("sp_qianlong__jiushi") then
        room:handleAddLoseSkills(player, "sp_qianlong__jiushi")
      end
      if player:getMark("@sp__qianlong_daoxin") >= 75 and not player:hasSkill("sp_qianlong__fangzhu") then
        room:handleAddLoseSkills(player, "sp_qianlong__fangzhu")
      end
      if player:getMark("@sp__qianlong_daoxin") >= 99 and not player:hasSkill("spjuejin") then
        room:handleAddLoseSkills(player, "spjuejin")
      end
    end
  end,

  refresh_events = {fk.EventAcquireSkill, fk.EventLoseSkill},
  can_refresh = function (self, event, target, player, data)
    return target == player and data == self
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.EventAcquireSkill then
      if player:getMark("@sp__qianlong_daoxin") >= 25 and not player:hasSkill("sp_qianlong__qingzheng") then
        room:handleAddLoseSkills(player, "sp_qianlong__qingzheng")
      end
      if player:getMark("@sp__qianlong_daoxin") >= 50 and not player:hasSkill("sp_qianlong__jiushi") then
        room:handleAddLoseSkills(player, "sp_qianlong__jiushi")
      end
      if player:getMark("@sp__qianlong_daoxin") >= 75 and not player:hasSkill("sp_qianlong__fangzhu") then
        room:handleAddLoseSkills(player, "sp_qianlong__fangzhu")
      end
      if player:getMark("@sp__qianlong_daoxin") >= 99 and not player:hasSkill("spjuejin") then
        room:handleAddLoseSkills(player, "spjuejin")
      end
    else
      local toLose = {
        "-sp_qianlong__qingzheng",
        "-sp_qianlong__jiushi",
        "-sp_qianlong__fangzhu",
        "-spjuejin",
      }
      room:handleAddLoseSkills(player, table.concat(toLose, "|"))
    end
  end,
}
Fk:loadTranslationTable{
  ["sp__qianlong"] = "潜龙",
  [":sp__qianlong"] = "持恒技，如下情况时，你获得对应数量的道心值：当你造成1点伤害后——15点；当你受到1点伤害后——20点；当你获得牌后——5点。<br>你根据道心值视为拥有以下技能：25点-〖清正〗；50点-〖酒诗〗；75点-〖放逐〗；" ..
  "99点-〖决讨〗。你的道心值上限为99。",
  ["@sp__qianlong_daoxin"] = "道心值",
  ["$sp__qianlong1"] = "暗蓄忠君之士，以待破局之机！",
  ["$sp__qianlong2"] = "若安司马于外，或则皇权可收！",
  ["$sp__qianlong3"] = "朕为天子，岂忍威权日去！",
  ["$sp__qianlong4"] = "假以时日，必讨司马一族！",
  ["$sp__qianlong5"] = "权臣震主，竟视天子于无物！",
  ["$sp__qianlong6"] = "朕行之决矣！正使死又何惧？",
}

qianlong.permanent_skill = true
caomao:addSkill(qianlong)

local QLqingzheng = fk.CreateTriggerSkill{
  name = "sp_qianlong__qingzheng",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return
      target == player and
      player:hasSkill(self) and
      player.phase == Player.Play and
      table.find(player:getCardIds("h"), function(id) return Fk:getCardById(id).suit ~= Card.NoSuit end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getOtherPlayers(player), function(p) return not p:isKongcheng() end)
    if #targets > 0 then
      local to = room:askForChoosePlayers(
        player,
        table.map(targets, Util.IdMapper),
        1,
        1,
        "#sp_qianlong__qingzheng-choose",
        self.name,
        true
      )
      if #to > 0 then
        self.cost_data = to[1]
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = player.room:getPlayerById(self.cost_data)

    local suits = {}
    for _, id in ipairs(player.player_cards[Player.Hand]) do
      local suit = Fk:getCardById(id):getSuitString(true)
      if suit ~= "log_nosuit" then
        table.insertIfNeed(suits, suit)
      end
    end
    local choices = room:askForChoices(player, suits, 1, 1, self.name, "#sp_qianlong__qingzheng-discard", false)
    local cards = table.filter(player.player_cards[Player.Hand], function (id)
      return not player:prohibitDiscard(Fk:getCardById(id)) and table.contains(choices, Fk:getCardById(id):getSuitString(true))
    end)
    if #cards > 0 then
      room:throwCard(cards, self.name, player, player)
    end
    if player.dead then return end
    local cids = to.player_cards[Player.Hand]
    local cards1 = {}
    if #cids > 0 then
      local id1 = room:askForCardChosen(
        player,
        to,
        { card_data = { { "$Hand", cids }  } },
        self.name,
        "#sp_qianlong__qingzheng-throw"
      )
      cards1 = table.filter(cids, function(id) return Fk:getCardById(id).suit == Fk:getCardById(id1).suit end)
      room:throwCard(cards1, self.name, to, player)
    end
    if #cards > #cards1 and not to.dead then return end
  end,
}
Fk:loadTranslationTable{
  ["sp_qianlong__qingzheng"] = "清正",
  [":sp_qianlong__qingzheng"] = "持恒技，出牌阶段开始时，你可以选择一名有手牌的其他角色，你弃置一种花色的所有手牌，" ..
  "然后观看其手牌并选择一种花色的牌，其弃置所有该花色的手牌。",
  ["#sp_qianlong__qingzheng-choose"] = "清正：可以弃置一种花色的所有手牌，观看一名角色手牌并弃置其中一种花色",
  ["#sp_qianlong__qingzheng-discard"] = "清正：请选择一种花色的所有手牌弃置",
  ["#sp_qianlong__qingzheng-throw"] = "清正：弃置其一种花色的所有手牌",
  ["$sp_qianlong__qingzheng1"] = "朕虽不德，昧于大道，思与宇内共臻兹路。",
  ["$sp_qianlong__qingzheng2"] = "愿遵前人教诲，为一国明帝贤君。",
}

QLqingzheng.permanent_skill = true
caomao:addRelatedSkill(QLqingzheng)

local QLjiushi = fk.CreateViewAsSkill{
  name = "sp_qianlong__jiushi",
  anim_type = "support",
  prompt = "#sp_qianlong__jiushi-active",
  pattern = "analeptic",
  card_filter = Util.FalseFunc,
  before_use = function(self, player)
    player:turnOver()
    player:drawCards(1, self.name)
  end,
  view_as = function(self, cards)
    local c = Fk:cloneCard("analeptic")
    c.skillName = self.name
    return c
  end,
  enabled_at_play = function (self, player)
    return player.faceup
  end,
  enabled_at_response = function (self, player)
    return player.faceup
  end,
}
Fk:loadTranslationTable{
  ["sp_qianlong__jiushi"] = "酒诗",
  ["#sp_qianlong__jiushi_trigger"] = "酒诗",
  [":sp_qianlong__jiushi"] = "持恒技，当你需要使用【酒】时，若你的武将牌正面向上，你可以翻面并摸一张牌，视为使用一张【酒】。",
  ["#sp_qianlong__jiushi-active"] = "发动酒诗，翻面来视为使用一张【酒】",
  ["$sp_qianlong__jiushi1"] = "心愤无所表，下笔即成篇。",
  ["$sp_qianlong__jiushi2"] = "弃忧但求醉，醒后寻复来。",
}

QLjiushi.permanent_skill = true
caomao:addRelatedSkill(QLjiushi)
local QLfangzhu = fk.CreateTriggerSkill{
  name = "sp_qianlong__fangzhu",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1, "#sp_qianlong__fangzhu-choose:::"..player:getLostHp(), self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local num = player:getLostHp()
    if to.hp > 0 and #room:askForDiscard(to, num, num, true, self.name, true, nil, "#sp_qianlong__fangzhu-ask:::" .. num, false) > 0 then
      if not to.dead then room:loseHp(to, 1, self.name) end
    else
      to:drawCards(num, self.name)
      if not to.dead then to:turnOver() end
    end
  end,
}
Fk:loadTranslationTable{
  ["sp_qianlong__fangzhu"] = "放逐",
  [":sp_qianlong__fangzhu"] = "持恒技，当你受到伤害后，你可以令一名其他角色选择一项：1.弃置X张牌并失去1点体力；2.摸X张牌并翻面（X为你已损失的体力值）。",
  ["#sp_qianlong__fangzhu-choose"] = "放逐：你可令一名其他角色选择摸%arg张牌并翻面，或弃置%arg张牌并失去1点体力",
  ["#sp_qianlong__fangzhu-ask"] = "放逐：弃置%arg张牌并失去1点体力，或点击“取消”，摸%arg张牌并翻面",
  ["$sp_qianlong__fangzhu1"] = "卿当竭命纳忠，何为此逾矩之举！",
  ["$sp_qianlong__fangzhu2"] = "朕继文帝风流，亦当效其权略！",
}

QLfangzhu.permanent_skill = true
caomao:addRelatedSkill(QLfangzhu)
local spjuejin = fk.CreateTriggerSkill{
  name = "spjuejin",
  anim_type = "offensive",
  frequency = Skill.Limited,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
    and player.hp < 3 and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getAlivePlayers(), Util.IdMapper), 1, 1, "#spjuejin-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    if player.general == "SP_heg__caomao" then
      player.general = "SP_heg__caomao2"
      room:broadcastProperty(player, "general")
    elseif player.deputyGeneral == "SP_heg__caomao" then
      player.deputyGeneral = "SP_heg__caomao2"
      room:broadcastProperty(player, "deputyGeneral")
    end
    while true do
      if player.dead or to.dead then return end
      local id = room:getNCards(1, "bottom")[1]
      room:moveCards({
        ids = {id},
        toArea = Card.Processing,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
        proposer = player.id,
      })
      local card = Fk:getCardById(id, true)
      room:setPlayerMark(player, MarkEnum.BypassTimesLimit.."-tmp", 1)
      local canUse = player:canUse(card) and not player:prohibitUse(card)
      room:setPlayerMark(player, MarkEnum.BypassTimesLimit.."-tmp", 0)
      local tos
      if canUse then
        local targets = {}
        for _, p in ipairs({player, to}) do
          if not player:isProhibited(p, card) then
            if card.skill:modTargetFilter(p.id, {}, player.id, card, false) then
              table.insert(targets, p.id)
            end
          end
        end
        if #targets > 0 then
          if card.skill:getMinTargetNum() == 0 then
            if not card.multiple_targets then
              if table.contains(targets, player.id) then
                tos = {player.id}
              end
            else
              tos = targets
            end
            if not room:askForSkillInvoke(player, self.name, data, "#spjuejin-ask:::"..card:toLogString()) then
              tos = nil
            end
          elseif card.skill:getMinTargetNum() == 2 then
            if table.contains(targets, to.id) then
              local seconds = {}
              Self = player -- for targetFilter check
              for _, second in ipairs(room:getOtherPlayers(to)) do
                if card.skill:targetFilter(second.id, {to.id}, {}, card) then
                  table.insert(seconds, second.id)
                end
              end
              if #seconds > 0 then
                local temp = room:askForChoosePlayers(player, seconds, 1, 1, "#spjuejin-second:::"..card:toLogString(), self.name, true)
                if #temp > 0 then
                  tos = {to.id, temp[1]}
                end
              end
            end
          else
            if #targets == 1 then
              if room:askForSkillInvoke(player, self.name, data, "#spjuejin-use::"..targets[1]..":"..card:toLogString()) then
                tos = targets
              end
            else
              local temp = room:askForChoosePlayers(player, targets, 1, #targets, "#spjuejin-target:::"..card:toLogString(), self.name, true)
              if #temp > 0 then
                tos = temp
              end
            end
          end
        end
      end
      if tos then
        room:useCard({
          card = card,
          from = player.id,
          tos = table.map(tos, function(p) return {p} end) ,
          skillName = self.name,
          extraUse = true,
        })
      else
        room:delay(800)
        room:moveCards({
          ids = {id},
          fromArea = Card.Processing,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonPutIntoDiscardPile,
        })
        return
      end
    end
  end,
}
Fk:loadTranslationTable{
  ["spjuejin"] = "决讨",
  [":spjuejin"] = "持恒技，限定技，出牌阶段开始时，若你的体力值不大于2，你可以选择一名角色并依次使用牌堆底的牌直到你无法使用，这些牌不能指定除你和该角色以外的角色为目标。",
  ["#spjuejin-choose"] = "决讨：你可以指定一名其他角色，连续对你或其使用牌堆底牌直到不能使用！",
  ["#spjuejin-use"] = "决讨：是否对 %dest 使用%arg",
  ["#spjuejin-ask"] = "决讨：是否使用%arg",
  ["#spjuejin-target"] = "决讨：选择你使用%arg的目标",
  ["#spjuejin-second"] = "决讨：选择你使用%arg的副目标",
  ["$spjuejin1"] = "朕宁拼一死，逆贼安敢一战！",
  ["$spjuejin2"] = "朕安可坐受废辱，今日当与卿自出讨之！",
}
spjuejin.permanent_skill = true
caomao:addRelatedSkill(spjuejin)

local zhugedan = General(extension, "SP_heg__zhugedan", "wei", 4)
zhugedan.mainMaxHpAdjustedValue = -1
local shiliang = fk.CreateTriggerSkill{
  name = "heg_shiliang",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return  data.to ~= player and player:hasSkill(self) and data.to:getMark("@@shiliang-round") == 0 and not data.to.dead
    and player:inMyAttackRange(data.to)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = data.to
    room:drawCards(player,1,self.name)
    room:setPlayerMark(to, "@@shiliang-round", 1)
    room:setPlayerMark(player,"_shiliang",1)
    local choices = {"shiliang-discard"}
    if table.find(player.room.alive_players, function(p) return not player:inMyAttackRange(p) and not H.compareKingdomWith(p, player) end) then
      table.insert(choices, "shiliang-drawcard")
    end
    local choice = room:askForChoice(player, choices,self.name, "#heg_shiliang-choose")
    if choice == "shiliang-drawcard" then
      if player.dead then return end
      local tos = room:askForChoosePlayers(player, table.map(table.filter(room:getOtherPlayers(player), function(p)
      return not H.compareKingdomWith(p, player) and not player:inMyAttackRange(p) end), Util.IdMapper), 1, 1, "#shiliangdrawcard-choose", self.name, false)
      if #tos > 0 then
        local targets = room:getPlayerById(tos[1])
        room:doIndicate(player.id, {targets.id})
        room:drawCards(targets, 1, self.name)
      end
    else
      if not player:isKongcheng() then 
      room:askForDiscard(player,1,1,false,self.name,false,nil,"#heg_shiliang-discard")
      end
    end
  end,
  
}
local gongao = fk.CreateTriggerSkill{
  name = "heg_gongao",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.Deathed},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player 
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if not H.compareKingdomWith(target, player) then
    local choices = {"gongao-attackange","gongao-drawcard"}
    if player.dead then return end
    local choice = room:askForChoice(player, choices, self.name, "#heg_gongao-choose")
    if choice == "gongao-attackange" then
      room:addPlayerMark(player,"@gongao-addrang",1)
    else
      room:drawCards(player,1,self.name)
    end
    else
      room:addPlayerMark(player,"@gongao-removerang",1)
    end
  end,
}
local gongao_attackange = fk.CreateAttackRangeSkill{
  name = "#gongao_attackange",
  frequency = Skill.Compulsory,
  correct_func = function (self, from,to)
    local player = from
    local addnum = player:getMark("@gongao-addrang")
    local removenum = player:getMark("@gongao-removerang")
    if player:getMark("@gongao-addrang") > 0 then
      return addnum
    end
    if player:getMark("@gongao-removerang") > 0 then
      return -removenum
    end
    return 0
  end,
}
local xiejue = fk.CreateActiveSkill{
   name = "heg_xiejue",
   anim_type = "offensive",
   relate_to_place = "m",
   target_num = 1,
   frequency = Skill.Limited,
   can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
   end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return Self.id ~= to_select
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.tos[1])
    local n = math.abs(player:getAttackRange() - 1) --计算攻击范围
    local x = math.min(n,5)
    room:drawCards(player,x,self.name)
    room:setPlayerMark(player,"@gongao-addrang",0)
    room:setPlayerMark(player,"@gongao-removerang",0)
    room:addPlayerMark(to, "@@xiejue-turn")
    local targetRecorded = type(player:getMark("xiejue_target-turn")) == "table" and player:getMark("xiejue_target-turn") or {}
    table.insertIfNeed(targetRecorded, to.id)
    room:setPlayerMark(player,"xiejue_target-turn",targetRecorded)
    room:setPlayerMark(player,"xiejuefumian-turn",1) --负面效果标记
  end,
}
local xiejue_targetmod = fk.CreateTargetModSkill{
  name = "#xiejue_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    if card and to then
      local targetRecorded = player:getMark("xiejue_target-turn")
      return type(targetRecorded) == "table" and table.contains(targetRecorded, to.id)
    end
  end,
  bypass_distances = function(self, player, skill, card, to)
    if card and to then
      local targetRecorded = player:getMark("xiejue_target-turn")
      return type(targetRecorded) == "table" and table.contains(targetRecorded, to.id)
    end
  end,
}
local xiejue_fumian = fk.CreateTriggerSkill{
  name = "#heg_xiejue_fumian",
  events = {fk.TurnEnd},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:getMark("xiejuefumian-turn") ~= 0 then
      local logic = player.room.logic
      local deathevents = logic.event_recorder[GameEvent.Death] or Util.DummyTable
      return #deathevents == 0
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
      local n = player.maxHp - 1
      room:changeMaxHp(player, -n)
  end,

}
xiejue:addRelatedSkill(xiejue_targetmod)
xiejue:addRelatedSkill(xiejue_fumian)
gongao:addRelatedSkill(gongao_attackange)
zhugedan:addSkill(shiliang)
zhugedan:addSkill(gongao)
zhugedan:addSkill(xiejue)
Fk:loadTranslationTable{
  ["SP_heg__zhugedan"] = "诸葛诞",
  ["#SP_heg__zhugedan"] = "严毅威重",
  ["designer:SP_heg__zhugedan"] = "雪人&残月",
  ["illustrator:SP_heg__zhugedan"] = "木美人",
  ["heg_shiliang"] = "峙靓",
  [":heg_shiliang"] = "每当有其他角色于本轮首次受到伤害时，若其在你的攻击范围内，你可以摸一张牌，然后选择一项：1.令一名在你攻击范围外的其他势力角色摸一张牌；"..
  "2.你弃置一张牌。",
  ["heg_gongao"] = "肱獒",
  [":heg_gongao"] = "锁定技，当一名角色死亡时，若其与你势力不同，你需执行下列选项中一项:1.攻击范围+1; 2.摸一张牌；若其与你势力相同，你的攻击范围-1。",
  ["heg_xiejue"] = "薤决",
  [":heg_xiejue"] = "主将技，限定技，此武将牌上的单独阴阳鱼个数-1。出牌阶段，你可以将你的攻击范围调整至1并摸X张牌，然后选择一名其他角色，本回合内对其使用牌无距离次数限制；"..
  "结束阶段，若本回合内没有角色死亡，你将体力上限调整至1。(X为你的攻击范围与1的差值且至多为5)",
  ["#heg_shiliang-choose"] = "峙靓：选择一项",
  ["#shiliangdrawcard-choose"] = "峙靓：选择一名在你攻击范围外的其他势力角色摸一张牌",
  ["#heg_shiliang-discard"] = "峙靓：你弃置一张手牌",
  ["shiliang-drawcard"]= "令一名在你攻击范围外的其他势力角色摸一张牌",
  ["shiliang-discard"] = "弃置一张手牌",
  ["@@shiliang-round"] =  " 峙靓 已发动",
  ["gongao-attackange"] ="攻击范围+1",
  ["gongao-drawcard"] = "摸一张牌",
  ["@gongao-addrang"]="攻击范围+",
  ["@gongao-removerang"]="攻击范围-",
  ["#heg_gongao-choose"] = "选择一项",
  ["@@xiejue-turn"] = "薤决",
  ["#heg_xiejue_fumian"] = "",

  ["$heg_shiliang1"] = "冒犯天威，当有此命！",
  ["$heg_shiliang2"] = "又一个倒在我脚下。",
  ["$heg_gongao1"]= "万事之功可成！",
  ["$heg_gongao2"] = "犯大魏者，虽远必诛！",
  ["$heg_xiejue1"] = "以有道之师，伐无道之徒！",
  ["$heg_xiejue2"] = "念先王之祀，当举义伐之。",
  ["~SP_heg__zhugedan"]="大丈夫，死则死已！",
}


local dongyun = General(extension, "SP_heg__dongyun", "shu", 3)
local spbingzheng = fk.CreateActiveSkill{
  name = "spbingzheng",
  anim_type = "drawcard",
  min_card_num = 0,
  target_num = 0,
  prompt = function (self, selected_cards, selected_targets)
    if Self:getHandcardNum() % 2 ~= 0 then
      return "#spbingzheng2:::"..(Self:getHandcardNum() // 2)
    else
      return "#spbingzheng1"
    end
  end,
  can_use = function(self, player)
    if player:getHandcardNum() % 2 ~= 0 then
      return not player:isKongcheng() and player:getMark("spbingzheng2-phase") == 0 and player:getMark("spbingzheng1-phase") == 0
    else
      return player:getMark("spbingzheng2-phase") == 0 and player:getMark("spbingzheng1-phase") == 0
    end
  end,
  card_filter = function (self, to_select, selected, selected_targets)
    if Self:getHandcardNum() % 2 ~= 0 then
      return Fk:currentRoom():getCardArea(to_select) == Player.Hand and not Self:prohibitDiscard(Fk:getCardById(to_select))
    else
      return false
    end
  end,
  target_filter = Util.FalseFunc,
  feasible = function (self, selected, selected_cards)
    if Self:getHandcardNum() % 2 ~= 0 then
      return #selected_cards > (Self:getHandcardNum() // 2)
    else
      return true
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    if player:getHandcardNum() % 2 ~= 0 then
      room:setPlayerMark(player, "spbingzheng2-phase", 1)
      room:throwCard(effect.cards, self.name, player, player)
      if not player.dead then
        player:drawCards(2, self.name)
      end
    else
      room:setPlayerMark(player, "spbingzheng1-phase", 1)
      player:drawCards(2, self.name)
      if not player.dead and not player:isKongcheng() then
        room:askForDiscard(player, player:getHandcardNum() // 2, 999, false, self.name, false, ".",
          "#spbingzheng-discard:::"..(player:getHandcardNum() // 2))
      end
    end
  end,
}
local sheyan = fk.CreateTriggerSkill{
  name = "ldsheyan",
  anim_type = "control",
  events = {fk.TargetConfirming},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and data.card:isCommonTrick() and data.card.trueName ~= "threaten_emperor"
        and data.card.trueName ~= "heg_zhaoshu" and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 then
      local room = player.room
      local targets = room:getUseExtraTargets(data, true, true)
      local origin_targets = U.getActualUseTargets(room, data, event)
      if #origin_targets > 1 then
        table.insertTable(targets, origin_targets)
      end
      if #targets > 0 then
        self.cost_data = targets
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, self.cost_data, 1, 1,
    "#ldsheyan-choose:::"..data.card:toLogString(), self.name, true, false, "addandcanceltarget_tip", AimGroup:getAllTargets(data.tos))
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if table.contains(AimGroup:getAllTargets(data.tos), self.cost_data) then
      AimGroup:cancelTarget(data, self.cost_data)
      return self.cost_data == player.id
    else
      AimGroup:addTargets(player.room, data, self.cost_data)
    end
  end,
}
dongyun:addSkill(spbingzheng)
dongyun:addSkill(sheyan)
Fk:loadTranslationTable{
  ["SP_heg__dongyun"] = "董允",
  ["#SP_heg__dongyun"] = "骨鲠良相",
  ["spbingzheng"] = "秉正",
  [":spbingzheng"] = "出牌阶段限一次，若你的手牌数为：偶数，你可以摸两张牌，然后弃置至少半数手牌；奇数，你可以弃置至少半数手牌，然后摸两张牌。",
  ["ldsheyan"] = "舍宴",
  [":ldsheyan"] = "每回合限一次，当你成为一张普通锦囊牌的目标时，你可以为此牌增加一个目标或减少一个目标（目标数至少为一）。",
  ["#spbingzheng1"] = "秉正：你可以摸两张牌，然后弃置至少半数手牌",
  ["#spbingzheng2"] = "秉正：你可以弃置至少半数手牌，然后摸两张牌",
  ["#spbingzheng-discard"] = "秉正：请弃置至少半数手牌",
  ["#ldsheyan-choose"] = "舍宴：你可以为%arg增加/减少一个目标",
  ["$spbingzheng1"] = "自古，就是邪不胜正！",
  ["$spbingzheng2"] = "主公面前，岂容小人搬弄是非！",
  ["$ldsheyan1"] = "公事为重，宴席不去也罢。",
  ["$ldsheyan2"] = "还是改日吧。",
  ["~SP_heg__dongyun"] = "大汉，要亡于宦官之手了……",
}

local SP_heg__haopu = General(extension, "SP_heg__haopu", "shu", 4)
local SP_heg__zhenying = fk.CreateActiveSkill{
  name = "SP_heg__zhenying",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#SP_heg__zhenying",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 1
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and Self:getHandcardNum() >= Fk:currentRoom():getPlayerById(to_select):getHandcardNum()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local tos = {player, target}
    local cardsMap = {}
    for _, p in ipairs(tos) do
      local choices = {"0", "1", "2"}
      p.request_data = json.encode({choices, choices, self.name, "#SP_heg__zhenying-choice"})
      cardsMap[p.id] = table.filter(p:getCardIds("h"), function(id)
        return not p:prohibitDiscard(Fk:getCardById(id))
      end)
    end
    room:notifyMoveFocus(tos, self.name)
    room:doBroadcastRequest("AskForChoice", tos)
    local discard_num_map = {}
    for _, p in ipairs(tos) do
      local choice = p.reply_ready and tonumber(p.client_reply) or 2
      discard_num_map[p.id] = p:getHandcardNum() - choice
    end
    local toAsk = {}
    for _, p in ipairs(tos) do
      local num = math.min(discard_num_map[p.id], #cardsMap[p.id])
      if num > 0 then
        table.insert(toAsk, p)
        local extra_data = {
          num = num,
          min_num = num,
          include_equip = false,
          skillName = self.name,
          pattern = ".",
          reason = self.name,
        }
        p.request_data = json.encode({ "discard_skill", "#AskForDiscard:::"..num..":"..num, false, extra_data })
      end
    end
    if #toAsk > 0 then
      local moveInfos = {}
      room:notifyMoveFocus(tos, self.name)
      room:doBroadcastRequest("AskForUseActiveSkill", toAsk)
      for _, p in ipairs(toAsk) do
        local throw
        if p.reply_ready then
          local replyCard = json.decode(p.client_reply).card
          throw = json.decode(replyCard).subcards
        else
          throw = table.random(cardsMap[p.id], discard_num_map[p.id])
        end
        table.insert(moveInfos, {
          ids = throw,
          from = p.id,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonDiscard,
          proposer = p.id,
          skillName = self.name,
        })
      end
      room:moveCards(table.unpack(moveInfos))
    end
    for _, p in ipairs(tos) do
      if not p.dead then
        local num = discard_num_map[p.id]
        if num < 0 then
          p:drawCards(-num, self.name)
        end
      end
    end
    if not player.dead and not target.dead and player:getHandcardNum() ~= target:getHandcardNum() then
      local from, to = player, target
      if player:getHandcardNum() > target:getHandcardNum() then
        from, to = target, player
      end
      room:useVirtualCard("duel", nil, from, to, self.name)
    end
  end,
}
SP_heg__haopu:addSkill(SP_heg__zhenying)
Fk:loadTranslationTable{
  ["SP_heg__haopu"] = "郝普",
  ["#SP_heg__haopu"] = "惭恨入地",
  ["designer:SP_heg__haopu"] = "何如",
  ["illustrator:SP_heg__haopu"] = "匠人绘",
  ["SP_heg__zhenying"] = "镇荧",
  [":SP_heg__zhenying"] = "出牌阶段限一次，你可以与一名手牌数不大于你的其他角色同时摸或弃置手牌至至多两张，然后手牌数较少的角色视为对另一名角色使用【决斗】。",
  ["#SP_heg__zhenying"] = "镇荧：与一名手牌数不大于你的其他角色同时选择将手牌调整至 0~2",
  ["#SP_heg__zhenying-choice"] = "镇荧：选择你要调整至的手牌数",
  ["#SP_heg__zhenying-discard"] = "镇荧：请弃置%arg张手牌",
  ["$SP_heg__zhenying1"] = "吾闻世间有忠义，今欲为之。",
  ["$SP_heg__zhenying2"] = "吴虽兵临三郡，普宁死不降。",
  ["~SP_heg__haopu"] = "徒做奔臣，死无其所……",
}

local huangquan = General(extension, "SP_heg__huangquan", "shu", 3)
local zhbh_heg__quanjian = fk.CreateActiveSkill{
  name = "zhbh_heg__quanjian",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:getMark("zhbh_heg__quanjian1-phase") == 0 and player:getMark("zhbh_heg__quanjian2-phase") == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    if #selected == 0 and to_select ~= Self.id then
      if Self:getMark("zhbh_heg__quanjian2-phase") == 0 then
        return true
      else
        for _, p in ipairs(Fk:currentRoom().alive_players) do
          if Fk:currentRoom():getPlayerById(to_select):inMyAttackRange(p) then
            return true
          end
        end
      end
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local targets = {}
    for _, p in ipairs(room:getOtherPlayers(target)) do
      if target:inMyAttackRange(p) then
        table.insert(targets, p.id)
      end
    end
    local choices = {}
    if player:getMark("zhbh_heg__quanjian1-phase") == 0 and #targets > 0 then
      table.insert(choices, "zhbh_heg__quanjian1")
    end
    if player:getMark("zhbh_heg__quanjian2-phase") == 0 then
      table.insert(choices, "zhbh_heg__quanjian2")
    end
    local choice = room:askForChoice(player, choices, self.name)
    room:addPlayerMark(player, choice.."-phase", 1)
    local to
    if choice == "zhbh_heg__quanjian1" then
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#zhbh_heg__quanjian-choose", self.name)
      if #tos > 0 then
        to = tos[1]
      else
        to = table.random(targets)
      end
      room:doIndicate(target.id, {to})
    end
    local choices2 = {"zhbh_heg__quanjian_cancel"}
    if choice == "zhbh_heg__quanjian1" then
      table.insert(choices2, 1, "zhbh_heg__quanjian_damage")
    else
      table.insert(choices2, 1, "zhbh_heg__quanjian_draw")
    end
    local choice2 = room:askForChoice(target, choices2, self.name)
    if choice2 == "zhbh_heg__quanjian_damage" then
      room:damage{
        from = target,
        to = room:getPlayerById(to),
        damage = 1,
        skillName = self.name,
      }
    elseif choice2 == "zhbh_heg__quanjian_draw" then
      if #target.player_cards[Player.Hand] < math.min(target:getMaxCards(), 5) then
        target:drawCards(math.min(target:getMaxCards(), 5) - #target.player_cards[Player.Hand])
      end
      if #target.player_cards[Player.Hand] > target:getMaxCards() then
        local n = #target.player_cards[Player.Hand] - target:getMaxCards()
        room:askForDiscard(target, n, n, false, self.name, false)
      end
      room:addPlayerMark(target, "zhbh_heg__quanjian_prohibit-turn", 1)
    else
      room:addPlayerMark(target, "zhbh_heg__quanjian_damage-turn", 1)
    end
  end,
}
local zhbh_heg__quanjian_prohibit = fk.CreateProhibitSkill{
  name = "#zhbh_heg__quanjian_prohibit",
  prohibit_use = function(self, player, card)
    return player:getMark("zhbh_heg__quanjian_prohibit-turn") > 0
  end,
}
local zhbh_heg__quanjian_record = fk.CreateTriggerSkill{
  name = "#zhbh_heg__quanjian_record",
  anim_type = "offensive",

  refresh_events = {fk.DamageInflicted},
  can_refresh = function(self, event, target, player, data)
    return target:getMark("zhbh_heg__quanjian_damage-turn") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    data.damage = data.damage + target:getMark("zhbh_heg__quanjian_damage-turn")
    player.room:setPlayerMark(target, "zhbh_heg__quanjian_damage-turn", 0)
  end,
}
local zhbh_heg__tujue = fk.CreateTriggerSkill{
  name = "zhbh_heg__tujue",
  anim_type = "defensive",
  frequency = Skill.Limited,
  events = {fk.AskForPeaches},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.dying and not player:isNude() and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1, "#zhbh_heg__tujue-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = player:getCardIds("he")
    room:moveCardTo(cards, Card.PlayerHand, room:getPlayerById(self.cost_data), fk.ReasonGive, self.name, nil, false, player.id)
    player:drawCards(#cards, self.name)
  end,
}
zhbh_heg__quanjian:addRelatedSkill(zhbh_heg__quanjian_prohibit)
zhbh_heg__quanjian:addRelatedSkill(zhbh_heg__quanjian_record)
huangquan:addSkill(zhbh_heg__quanjian)
huangquan:addSkill(zhbh_heg__tujue)
Fk:loadTranslationTable{
  ["SP_heg__huangquan"] = "黄权",
  ["#SP_heg__huangquan"] = "忠事三朝",
  ["designer:SP_heg__huangquan"] = "头发好借好还",
  ["illustrator:SP_heg__huangquan"] = "匠人绘",
  ["zhbh_heg__quanjian"] = "忠谏",
  [":zhbh_heg__quanjian"] = "出牌阶段限一次，你选择以下一项令一名其他角色选择是否执行：1.对一名其攻击范围内你指定的角色造成1点伤害。"..
  "2.将手牌调整至手牌上限（最多摸到5张），其不能使用手牌直到回合结束。若其不执行，则其本回合下次受到的伤害+1。",
  ["zhbh_heg__tujue"] = "途绝",
  [":zhbh_heg__tujue"] = "限定技，当你处于濒死状态时，你可以将所有牌交给一名其他角色，然后你摸等量的牌。",
  ["zhbh_heg__quanjian1"] = "对一名其攻击范围内你指定的角色造成1点伤害",
  ["zhbh_heg__quanjian2"] = "将手牌调整至手牌上限（最多摸到5张），其不能使用手牌直到回合结束",
  ["#zhbh_heg__quanjian-choose"] = "忠谏：选择一名其攻击范围内的角色",
  ["zhbh_heg__quanjian_damage"] = "对指定的角色造成1点伤害",
  ["zhbh_heg__quanjian_draw"] = "将手牌调整至手牌上限（最多摸到5张），不能使用手牌直到回合结束",
  ["zhbh_heg__quanjian_cancel"] = "不执行，本回合下次受到的伤害+1",
  ["#zhbh_heg__tujue-choose"] = "途绝：你可以将所有牌交给一名其他角色",
  ["$zhbh_heg__quanjian1"] = "陛下宜后镇，臣请为先锋！",
  ["$zhbh_heg__quanjian2"] = "吴人悍战，陛下万不可涉险！",
  ["$zhbh_heg__tujue1"] = "归蜀无路，孤臣泪尽江北。",
  ["$zhbh_heg__tujue2"] = "受吾主殊遇，安能降吴！",
  ["~SP_heg__huangquan"] = "败军之将，何言忠乎？",
}

local SP_heg__sunhong = General:new(extension, "SP_heg__sunhong", "wu", 3, 3, General.Male)
local spxianbi = fk.CreateTriggerSkill{
  name = "spxianbi",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = {}
    room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
      local use = e.data[1]
      if use.from ~= player.id and table.find(TargetGroup:getRealTargets(use.tos), function(pid) return pid == player.id end) then
        table.insertIfNeed(targets, use.from)
      end
    end, Player.HistoryTurn)
    if #targets == 0 then return false end
    -- for _, pid in ipairs(targets) do
    --   room:setPlayerMark(room:getPlayerById(pid), "_spxianbi_slash-phase", 1)
    -- end
    local _, ret = room:askForUseViewAsSkill(player, "#spxianbi_vs", "#spxianbi-choose", true, {bypass_distances = true, bypass_times = true, exclusive_targets = targets})
    for _, pid in ipairs(targets) do
      room:setPlayerMark(room:getPlayerById(pid), "_spxianbi_slash-phase", 0)
    end
    if ret then
      self.cost_data = {ret.cards, ret.targets}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards, tos = table.unpack(self.cost_data)
    local card = Fk:cloneCard("slash")
    card:addSubcards(cards)
    card.skillName = "spxianbi"
    room:useCard{
      from = player.id,
      tos = table.map(tos, function(p) return {p} end),
      card = card
    }
    if (card.color == Card.Black or card.color ~= Card.Black) then
      player:drawCards(1, self.name)
    end
  end,
}
local spxianbi_vs = fk.CreateViewAsSkill{
  name = "#spxianbi_vs",
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, cards)
    if #cards < 1 then return end
    local card = Fk:cloneCard("slash")
    card:addSubcards(cards)
    card.skillName = "spxianbi"
    return card
  end
}
local spzenrun = fk.CreateTriggerSkill{
  name = "spzenrun",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card and data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(data.to)
    local card = room:askForCard(to, 1, 1, false, self.name, true, ".|.|.|hand|.|.", "#spzenrun_give:" .. player.id)
    if #card > 0 then
      room:obtainCard(player, card, false, fk.ReasonGive, data.to)
    else
      data.disresponsiveList = data.disresponsiveList or {}
      table.insert(data.disresponsiveList, data.to)
    end
  end,
}
Fk:addSkill(spxianbi_vs)
SP_heg__sunhong:addSkill(spxianbi)
SP_heg__sunhong:addSkill(spzenrun)
Fk:loadTranslationTable{
  ["SP_heg__sunhong"] = "孙弘",
  ["#SP_heg__sunhong"] = "谮诉构争",
  ["illustrator:SP_heg__sunhong"] = "匠人绘",
  ["spxianbi"] = "险诐",
  [":spxianbi"] = "一名角色的结束阶段，你可以将一张牌当【杀】对一名本回合对你使用过牌的其他角色使用，此【杀】结算后你摸一张牌。",
  ["spzenrun"] = "谮润",
  [":spzenrun"] = "锁定技，当你使用【杀】指定目标后，其选择一项：1.交给你一张手牌；2.不可响应此【杀】。",
  ["#spxianbi_vs"] = "险诐",
  ["#spxianbi_prohibit"] = "险诐",
  ["#spxianbi-choose"] = "险诐：你可以将一张手牌当【杀】对一名本回合对你使用过牌的其他角色使用",
  ["#spzenrun_give"] = "谮润：你需交给 %src 一张手牌，否则你不可响应此【杀】",
  ["$spxianbi1"] = "宦海如薄冰，求生逐富贵。",
  ["$spxianbi2"] = "吾不欲为鱼肉，故为刀俎。",
  ["$spzenrun1"] = "据图谋不轨，今奉诏索命。",
  ["$spzenrun2"] = "休妄论芍陂之战，当诛之。",
  ["~SP_heg__sunhong"] = "诸葛公何至于此……",
}

local SP_heg__sunhao = General(extension, "SP_heg__sunhao", "wu", 4)
local SP_heg__canshi = fk.CreateTriggerSkill{
  name = "SP_heg__canshi",
  anim_type = "drawcard",
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and table.find(player.room.alive_players, function (p)
      return p:isWounded() or ((p.kingdom == "wu" and player.kingdom == "wu") or player.kingdom ~= "wu")
    end)
  end,
  on_cost = function (self, event, target, player, data)
    local n = 0
    for _, p in ipairs(player.room.alive_players) do
      if p:isWounded() or (player:hasSkill("guiming") and p.kingdom == "wu" and p ~= player) then
        n = n + 1
      end
    end
    n = math.max(1,n)
    n = math.min(3,n)
    if player.room:askForSkillInvoke(player, self.name, nil, "#SP_heg__canshi-invoke:::"..n) then
      self.cost_data = n
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    data.n = data.n + self.cost_data
  end,
}
local SP_heg__chouhai = fk.CreateTriggerSkill{
  name = "SP_heg__chouhai",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events ={fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:isKongcheng()
  end,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage + 1
  end,
}
local malar = fk.CreateTriggerSkill{
  name = "#malar",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, {"弃置所有手牌", "loseHp"}, self.name)
    if choice == "弃置所有手牌" then
      player:throwAllCards("h")
    else
      room:loseHp(player, 1, self.name)
    end
  end,
}
SP_heg__sunhao:addSkill(SP_heg__canshi)
SP_heg__chouhai:addRelatedSkill(malar)
SP_heg__sunhao:addSkill(SP_heg__chouhai)
Fk:loadTranslationTable{
  ["SP_heg__sunhao"] = "孙皓",
  ["#SP_heg__sunhao"] = "时日曷丧",
  ["designer:SP_heg__sunhao"] = "韩旭",
  ["SP_heg__canshi"] = "残蚀",
  [":SP_heg__canshi"] = "摸牌阶段，你可以多摸X张牌（X为已受伤的角色数且至少为1，至多为3）。此时所有与你势力相同的角色均视为已受伤。",
  ["#SP_heg__canshi_delay"] = "残蚀",
  ["SP_heg__chouhai"] = "仇海",
  [":SP_heg__chouhai"] = "锁定技，结束阶段，你选择一项：1.弃置所有手牌（无牌则不弃，不足全弃）；2.失去1点体力。当你受到【杀】造成的伤害时，若你没有手牌，此伤害+1。",
  ["#SP_heg__canshi-invoke"] = "残蚀：你可以多摸 %arg 张牌",
  ["#malar"] = "仇海",
  ["$SP_heg__canshi1"] = "这是要我命归黄泉吗？",
  ["$SP_heg__canshi2"] = "这就是末世皇帝的不归路！",
  ["$SP_heg__chouhai1"] = "哼，树敌三千又如何？",
  ["$SP_heg__chouhai2"] = "不发狂，就灭亡！",
  ["~SP_heg__sunhao"] = "命啊！命！",
}

local tengyin = General(extension, "SP_heg__tengyin", "wu", 3)
tengyin:addCompanions("ze_heg__zhugeke")
local mingche_prohibit = fk.CreateProhibitSkill{
  name = "#mingche_prohibit",
  prohibit_use = function(self, player, card)
    if card then
      for _, id in ipairs(Card:getIdList(card)) do
        if Fk:getCardById(id):getMark("#@@mingche-turn") ~= 0 then
          return true
        end
      end
    end
  end,
  prohibit_response = function(self, player, card)
    if card then
      for _, id in ipairs(Card:getIdList(card)) do
        if Fk:getCardById(id):getMark("#@@mingche-turn") ~= 0 then
          return true
        end
      end
    end
  end
}
local mingche_maxcard = fk.CreateMaxCardsSkill{
  name = "#mingche_maxcard",
  exclude_from = function(self, player, card)
    return card:getMark("#@@mingche-turn") ~= 0
  end
}
local mingche = fk.CreateTriggerSkill{
  name = "mingche",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if player.phase == Player.Play and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 then
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player.phase == Player.Play then
      local num = 3
      if num > 0 then
        player:drawCards(num, self.name)
        local all_cards = player:getCardIds("h")
        local cards = table.filter(all_cards, function(id)
          if not isPublished(player, id) then
            return true
          end
        end)
        num = math.min(#cards, num)
        local selected, _ = U.askforChooseCardsAndChoice(player, cards, {"OK"}, self.name, "#mingche-choose:::"..num, nil, num, num, all_cards)
        publish(player, selected)
        for _, id in ipairs(selected) do
          local card = Fk:getCardById(id)
          room:addCardMark(card, "@@mingche_Pub-inhand", 1)
          room:setCardMark(card, "#@@mingche-turn", 1)
        end
      end
    end
  end,
}
S.skillInfo(mingche, "明澈",
  "锁定技，当你于一个阶段使用第一张牌后，你摸三张牌，然后明置等量的手牌，以此法明置的牌于本回合内：不能被使用且不计入手牌上限。",
  {"君子如玉，德形皓白。","木秀于身，芬芳自如。"}
)
local anliur = fk.CreateTriggerSkill{
  name = "anliur",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events ={fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.damage >= 2
  end,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage + 1 
    local room = player.room
    local isMain = player.general == "zhbh_heg__tengyin" and true or false
    H.transformGeneral(room, player, isMain, 3, false)
  end,
}
mingche:addRelatedSkill(mingche_prohibit)
mingche:addRelatedSkill(mingche_maxcard)
tengyin:addSkill(mingche)
tengyin:addSkill(anliur)
Fk:loadTranslationTable{
  ["SP_heg__tengyin"] = "滕胤",
  ["#SP_heg__tengyin"] = "厉操遵蹈",
  ["illustrator:SP_heg__tengyin"] = "猎枭",
  ["anliur"] = "暗流",
  [":anliur"] = "锁定技，当你受到大于1点的伤害时，你令此伤害+1，且你须"..
  "变更此武将牌。",
  ["#mingche-choose"] = "请选择3张手牌明置",
  ["@@mingche_Pub-inhand"] = "明置",
  ["$anliur1"] = "国有其弊，上书当陈。",
  ["$anliur2"] = "食君之禄，怎可默言。",
  ["~SP_heg__tengyin"] = "臣好洁，不堪与之合污！",
}

local sunxiu = General(extension, "SP_heg__sunxiu", "wu", 3)
local yanzhu = fk.CreateActiveSkill{
  name = "SP_heg_yanzhu",
  anim_type = "defensive",
  target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 
  end,
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:drawCards(player,1,self.name)
    if player.dead then return end
    local to = room:askForChoosePlayers(player, table.map(table.filter(room:getOtherPlayers(player), function(p)
      return  p end), Util.IdMapper), 1, 1, "#yanzhu-choose", self.name, false)
      if #to > 0 then
        local target = room:getPlayerById(to[1])
        local id = room:askForCardChosen(player,player,"he",self.name,"#yanzhu-chosencard")
          room:obtainCard(target,{id},false,fk.ReasonGive)
         if  H.askCommandTo(player,target,self.name,false) then
         else
          local choices = {"yanzhu-discard","yanzhu-damaged"}
           local choice = room:askForChoice(target,choices,self.name)
           if choice == "yanzhu-discard" then
              room:askForDiscard(target,2,2,false,self.name,false,nil,"#yanzhu-discards")
           else
            room:damage{
              from = player,
              to = target,
              damage = 1,
              skillName = self.name,
            }
          end
        end
      end
  end,
}
sunxiu:addSkill(yanzhu)
sunxiu:addSkill("xingxue")
Fk:loadTranslationTable{
  ["SP_heg__sunxiu"] = "孙休",
  ["#SP_heg__sunxiu"] = "弥殇的景君",
  ["designer:SP_heg__sunxiu"] = "madman",
  ["illustrator:SP_heg__sunxiu"] = "NOVART",

  ["SP_heg_yanzhu"] = "宴诛",
  [":SP_heg_yanzhu"] = "出牌阶段限一次，你可以摸一张牌并将一张牌交给一名其他角色，然后令其执行一次“军令”。若其不执行，其选择一项：1.弃置两张手牌；2.受到你对其造成的1点伤害。",
  ["#yanzhu-choose"] = "宴诛：选择一名其他角色",
  ["#yanzhu-chosencard"] = "宴诛：选择一张牌",
  ["yanzhu-discard"] = "弃置两张手牌",
  ["yanzhu-damaged"] = "受到1点伤害",
  ["#yanzhu-discards"]="宴诛杀：弃置两张手牌",

  ["$SP_heg_yanzhu1"]="不诛此权臣，朕，何以治天下？",
  ["$SP_heg_yanzhu2"]="大局已定，你还是放弃吧！",
  ["~SP_heg__sunxiu"] = "崇文抑武，朕错了吗？",
}



local duyu = General(extension, "SP_heg__duyu", "qun", 4)
local spwuku = fk.CreateTriggerSkill{
  name = "spwuku",
  events = {fk.CardUsing},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target ~= player and player:hasSkill(self) and player:getMark("@spwuku") < 2 and data.card.type == Card.TypeEquip
  end,
  on_use = function(self, event, target, player)
    player.room:addPlayerMark(player, "@spwuku")
  end,
}
local spmiewu = fk.CreateViewAsSkill{
  name = "spmiewu",
  pattern = ".",
  expand_pile = "$carriage&",
  interaction = function()
    local names, all_names = {} , {}
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if (card.type == Card.TypeBasic or (card.type == Card.TypeTrick and card.sub_type ~= Card.SubtypeDelayedTrick and card.trueName ~= "threaten_emperor")) and not card.is_derived and not table.contains(all_names, card.name) then
        table.insert(all_names, card.name)
        local to_use = Fk:cloneCard(card.name)
        if ((Fk.currentResponsePattern == nil and Self:canUse(to_use) and not Self:prohibitUse(to_use)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(to_use))) then
          table.insert(names, card.name)
        end
      end
    end
    if #names == 0 then return false end
    return U.CardNameBox { choices = names, all_choices = all_names }
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and table.contains(Self:getHandlyIds(true), to_select)
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    player.room:removePlayerMark(player, "@spwuku")
  end,
  enabled_at_play = function(self, player)
    return player:getMark("@spwuku") > 0 and player:usedSkillTimes(self.name) == 0
  end,
  enabled_at_response = function(self, player, response)
    return player:getMark("@spwuku") > 0 and player:usedSkillTimes(self.name) == 0
  end,
}
local spmiewu_delay = fk.CreateTriggerSkill{
  name = "#spmiewu_delay",
  events = {fk.CardUseFinished, fk.CardRespondFinished},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return not player.dead and player == target and table.contains(data.card.skillNames, spmiewu.name)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, spmiewu.name)
  end,
}
duyu:addSkill(spwuku)
spmiewu:addRelatedSkill(spmiewu_delay)
duyu:addSkill(spmiewu)
Fk:loadTranslationTable{
  ["SP_heg__duyu"] = "杜预",
  ["#SP_heg__duyu"] = "文成武德",
  ["illustrator:SP_heg__duyu"] = "鬼画府",
  ["spwuku"] = "武库",
  [":spwuku"] = "锁定技，当其他角色使用装备牌时，你获得1个“武库”标记。（“武库”数量至多为2）",
  ["@spwuku"] = "武库",
  ["spmiewu"] = "灭吴",
  ["#spmiewu_delay"] = "灭吴",
  [":spmiewu"] = "每回合限一次，你可以弃置1个“武库”，将一张牌当做任意一张基本牌或普通锦囊牌（【挟天子以令诸侯】除外）使用或打出；若如此做，你摸一张牌。",
  ["$spwuku1"] = "损益万枢，竭世运机。",
  ["$spwuku2"] = "胸藏万卷，充盈如库。",
  ["$spsanchen1"] = "贼计已穷，陈兵吴地，可一鼓而下也。",
  ["$spsanchen2"] = "伐吴此举，十有九利，惟陛下察之。",
  ["$spmiewu1"] = "倾荡之势已成，石城尽在眼下。",
  ["$spmiewu2"] = "吾军势如破竹，江东六郡唾手可得。",
  ["~SP_heg__duyu"] = "洛水圆石，遂道向南，吾将以俭自完耳……",
}

local himiko = General(extension, "SP_heg__himiko", "qun", 3)--卑弥呼
local guishu = fk.CreateViewAsSkill{
  name = "heg_guishu",
  pattern = "known_both,befriend_attacking",
  anim_type = "drawcard",
  expand_pile = "$carriage&",
  interaction = function()
    local names = {}
    local all_choices = {"befriend_attacking", "known_both"}
    for _, name in ipairs(all_choices) do
      if Self:getMark("_guishu-turn") ~= name and Self:canUse(Fk:cloneCard(name)) then
        table.insertIfNeed(names, name)
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names, all_choices = all_choices }
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).suit == Card.Spade
      and Fk:currentRoom():getCardArea(to_select) == Player.Hand and table.contains(Self:getHandlyIds(true), to_select)
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or self.interaction.data == nil then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
  before_use = function(self, player, use)
    player.room:setPlayerMark(player, "_guishu-turn", use.card.name)
  end
}

local yuanyuk = fk.CreateTriggerSkill{
  name = "heg_yuanyuk",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from and not data.from:inMyAttackRange(target)
  end,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage - 1
  end
}

himiko:addSkill(guishu)
himiko:addSkill(yuanyuk)

Fk:loadTranslationTable{
  ['SP_heg__himiko'] = '卑弥呼', -- 十年心版
  ["#SP_heg__himiko"] = "邪马台的女王",
  ["illustrator:SP_heg__himiko"] = "聚一_小道恩",
  ["designer:SP_heg__himiko"] = "淬毒",

  ["heg_guishu"] = "鬼术",
  [":heg_guishu"] = "出牌阶段，你可将一张♠手牌当【远交近攻】或【知己知彼】使用（不可与你此回合上一次以此法使用的牌相同）。",
  ["heg_yuanyuk"] = "远域",
  [":heg_yuanyuk"] = "锁定技，当你受到伤害时，若有伤害来源且你不在伤害来源的攻击范围内，此伤害-1。",

  ["$heg_guishu1"] = "契约已定！",
  ["$heg_guishu2"] = "准备好，听候女王的差遣了吗？",
  ["$heg_yuanyuk1"] = "是你，在召唤我吗？",
  ["$heg_yuanyuk2"] = "这片土地的人，真是太有趣了。",
  ["~SP_heg__himiko"] = "我还会从黄泉比良坂回来的……",
}

local SP_heg__shichangshi = General(extension, "SP_heg__shichangshi", "qun", 3)
Fk:loadTranslationTable{
  ["SP_heg__shichangshi"] = "十常侍",
}
local tenChangShiMapper = {
  ["SP_heg__changshi__zhangrang"] = "SP_heg__changshi__taoluan",
  ["SP_heg__changshi__zhaozhong"] = "SP_heg__changshi__chiyan",
  ["SP_heg__changshi__sunzhang"] = "SP_heg__changshi__zimou",
  ["SP_heg__changshi__bilan"] = "SP_heg__changshi__picai",
  ["SP_heg__changshi__xiayun"] = "SP_heg__changshi__yaozhuo",
  ["SP_heg__changshi__hankui"] = "SP_heg__changshi__xiaolu",
  ["SP_heg__changshi__lisong"] = "SP_heg__changshi__kuiji",
  ["SP_heg__changshi__duangui"] = "SP_heg__changshi__chihe",
  ["SP_heg__changshi__guosheng"] = "SP_heg__changshi__niqu",
  ["SP_heg__changshi__gaowang"] = "SP_heg__changshi__miaoyu",
}

Fk:loadTranslationTable{
  ["changshi"] = "常侍",
  ["SP_heg__changshi__zhangrang"] = "张让",
  ["SP_heg__changshi__zhaozhong"] = "赵忠",
  ["SP_heg__changshi__sunzhang"] = "孙璋",
  ["SP_heg__changshi__bilan"] = "毕岚",
  ["SP_heg__changshi__xiayun"] = "夏恽",
  ["SP_heg__changshi__hankui"] = "韩悝",
  ["SP_heg__changshi__lisong"] = "栗嵩",
  ["SP_heg__changshi__duangui"] = "段珪",
  ["SP_heg__changshi__guosheng"] = "郭胜",
  ["SP_heg__changshi__gaowang"] = "高望",

  [":SP_heg__changshi__zhangrang-specificSkillDesc"] = "滔乱：（滔乱）",
  [":SP_heg__changshi__zhaozhong-specificSkillDesc"] = "鸱咽：（破军）",
  [":SP_heg__changshi__sunzhang-specificSkillDesc"] = "自谋：（勤政）",
  [":SP_heg__changshi__bilan-specificSkillDesc"] = "庀材：（慧识）",
  [":SP_heg__changshi__xiayun-specificSkillDesc"] = "谣诼：（义争）",
  [":SP_heg__changshi__hankui-specificSkillDesc"] = "宵赂：（巧思）",
  [":SP_heg__changshi__lisong-specificSkillDesc"] = "窥机：（魄袭）",
  [":SP_heg__changshi__duangui-specificSkillDesc"] = "叱吓：（烈弓）",
  [":SP_heg__changshi__guosheng-specificSkillDesc"] = "逆取：（评才）",
  [":SP_heg__changshi__gaowang-specificSkillDesc"] = "妙语：（龙魂）",
}

local hiddenspChangshi = General(extension, "hiddenspChangshi", "qun", 1)
hiddenspChangshi.total_hidden = true
local changshiTaoluan = fk.CreateViewAsSkill{
  name = "SP_heg__changshi__taoluan",
  pattern = ".",
  interaction = function()
    local names = {}
    local mark = Self:getMark("@$taoluan")
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if (card.type == Card.TypeBasic or (card:isCommonTrick() and card.trueName ~= "threaten_emperor")) and not card.is_derived and
        Self:canUse(card) then
        if mark == 0 or (not table.contains(mark, card.trueName)) then
          table.insertIfNeed(names, card.name)
        end
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names}
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcard(cards[1])
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return not player:isNude() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  enabled_at_response = function(self, player)
    return false
  end,
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__taoluan"] = "滔乱",
  [":SP_heg__changshi__taoluan"] = "出牌阶段限一次，你可以将一张牌当任意基本牌或普通锦囊牌（【挟天子以令诸侯】除外）使用。",
  ["$SP_heg__changshi__taoluan1"] = "罗绮朱紫，皆若吾等手中傀儡。",
}

hiddenspChangshi:addSkill(changshiTaoluan)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__taoluan")

local changshiChiyan = fk.CreateTriggerSkill{
  name = "SP_heg__changshi__chiyan",
  anim_type = "offensive",
  events = {fk.TargetSpecified, fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and data.card and data.card.trueName == "slash" then
      if event == fk.TargetSpecified then
        local to = player.room:getPlayerById(data.to)
        return not to.dead and to.hp > 0 and not to:isNude()
      elseif event == fk.DamageCaused then
        return not data.chain and #player:getCardIds(Player.Hand) >= #data.to:getCardIds(Player.Hand) and
        #player:getCardIds(Player.Equip) >= #data.to:getCardIds(Player.Equip)
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.TargetSpecified then
      if player.room:askForSkillInvoke(player, self.name, nil, "#SP_heg__changshi__chiyan-invoke::"..data.to) then
        player.room:doIndicate(player.id, {data.to})
        return true
      end
    elseif event == fk.DamageCaused then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecified then
      local to = room:getPlayerById(data.to)
      local cards = room:askForCardsChosen(player, to, 1, 1, "he", self.name)
      to:addToPile(self.name, cards, false, self.name)
    else
      data.damage = data.damage + 1
    end
  end,
}

local changshiChiyanDelay = fk.CreateTriggerSkill{
  name = "#SP_heg__changshi__chiyan_delay",
  mute = true,
  events = {fk.EventPhaseChanging},
  can_trigger = function(self, event, target, player, data)
    return data.to == Player.NotActive and #player:getPile("SP_heg__changshi__chiyan") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player.room:obtainCard(player.id, player:getPile("SP_heg__changshi__chiyan"), false)
  end,
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__chiyan"] = "鸱咽",
  [":SP_heg__changshi__chiyan"] = "出牌阶段限一次，当你使用【杀】指定目标后，你可以将其一张牌扣置于其武将牌旁，该角色于本回合结束时获得此牌；当你使用【杀】对手牌数和"..
  "装备区内的牌数均不大于你的目标角色造成伤害时，此伤害+1。",
  ["#SP_heg__changshi__chiyan-invoke"] = "是否对%dest发动 鸱咽",
  ["$SP_heg__changshi__chiyan1"] = "逆臣乱党，都要受这啄心之刑。",
}

changshiChiyan:addRelatedSkill(changshiChiyanDelay)
hiddenspChangshi:addSkill(changshiChiyan)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__chiyan")

local changshiZimou = fk.CreateTriggerSkill{
  name = "SP_heg__changshi__zimou",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return
      target == player and
      player:hasSkill(self) and
      player.phase == Player.Play and
      table.contains({ 1, 999, 999 }, player:getMark("#@" .. self.name))
  end,
  on_use = function(self, event, player, target, data)
    local count = player:getMark("#@" .. self.name)
    local cardList = "analeptic"
    if count == 999 then
      cardList = "slash"
    elseif count == 999 then
      cardList = "duel"
    end
    local randomCard = player.room:getCardsFromPileByRule(cardList)
    if #randomCard > 0 then
      player.room:moveCards({
        ids = { randomCard[1] },
        to = player.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonPrey,
        proposer = player.id,
        skillName = self.name,
      })
    end
  end,

  refresh_events = {fk.PreCardUse},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and player.phase == Player.Play
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:addPlayerMark(player, "#@" .. self.name, 1)
  end,
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__zimou"] = "自谋",
  [":SP_heg__changshi__zimou"] = "锁定技，当你于此阶段再使用一张牌时，你获得一张【酒】。",
  ["#@SP_heg__changshi__zimou"] = "自谋",
  ["$SP_heg__changshi__zimou1"] = "在宫里当差，还不是为这利字！",
}

hiddenspChangshi:addSkill(changshiZimou)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__zimou")

local changshiPicai = fk.CreateActiveSkill{
  name = "SP_heg__changshi__picai",
  anim_type = "drawcard",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    return false
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    return false
  end,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)

    local cardsJudged = {}
    while true do
      local parsePattern = table.concat(table.map(cardsJudged, function(card)
        return card:getSuitString()
      end), ",")

      local judge = {
        who = from,
        reason = self.name,
        pattern = ".|.|" .. (parsePattern == "" and "." or "^(" .. parsePattern .. ")"),
        skipDrop = true,
      }
      room:judge(judge)

      table.insert(cardsJudged, judge.card)

      if
        not table.every(cardsJudged, function(card)
          return card == judge.card or judge.card:compareSuitWith(card, true)
        end) or
        not room:askForSkillInvoke(from, self.name, nil, "#SP_heg__changshi__picai-ask")
      then
        break
      end
    end

    local alivePlayerIds = table.map(room.alive_players, function(p)
      return p.id
    end)

    cardsJudged = table.filter(cardsJudged, function(card)
      return room:getCardArea(card.id) == Card.Processing
    end)
    if #cardsJudged == 0 then
      return false
    end

    local targets = room:askForChoosePlayers(from, alivePlayerIds, 1, 1, "#SP_heg__changshi__picai-give", self.name, true)
    
    if #targets > 0 then
      room:moveCardTo(cardsJudged, Card.PlayerHand, room:getPlayerById(targets[1]), fk.ReasonGive, self.name, nil, true, from.id)
    else
      room:moveCards({
        ids = table.map(cardsJudged, function(card)
          return card:getEffectiveId()
        end),
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonPutIntoDiscardPile,
        skillName = self.name,
      })
    end
  end,
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__picai"] = "庀材",
  [":SP_heg__changshi__picai"] = "出牌阶段限一次，你可以进行判定，若结果与本次流程中的其他判定结果均不同，你可重复此流程。最后你可将本次流程中所有生效的判定牌"..
  "交给一名角色。",
  ["#SP_heg__changshi__picai-ask"] = "庀材：你可以重复此流程",
  ["#SP_heg__changshi__picai-give"] = "庀材：你可以将这些判定牌交给一名角色",
  ["$SP_heg__changshi__picai1"] = "修得广厦千万，可庇汉室不倾。",
}

hiddenspChangshi:addSkill(changshiPicai)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__picai")

local changshiYaozhuo = fk.CreateActiveSkill{
  name = "SP_heg__changshi__yaozhuo",
  anim_type = "control",
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected)
    return false
  end,
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return
      #selected < 1 and
      Self.id ~= to_select and
      Self:canPindian(target)
  end,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.tos[1])
    local pindian = from:pindian({ to }, self.name)
    if pindian.results[to.id].winner == from then
      room:setPlayerMark(to, "@@SP_heg__changshi__yaozhuo", true)
    else
      room:askForDiscard(from, 2, 2, true, self.name, false)
    end
  end,
}
local changshiYaozhuoDebuff = fk.CreateTriggerSkill{
  name = "#SP_heg__changshi__Yaozhuo-debuff",
  mute = true,
  priority = 3,
  refresh_events = {fk.EventPhaseChanging},
  can_refresh = function(self, event, target, player, data)
    return target:getMark("@@SP_heg__changshi__yaozhuo") == true and data.from == Player.RoundStart
  end,
  on_refresh = function(self, event, target, player, data)
    target.room:setPlayerMark(target, "@@SP_heg__changshi__yaozhuo", 0)
    target:skip(Player.Draw)
  end,
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__yaozhuo"] = "谣诼",
  [":SP_heg__changshi__yaozhuo"] = "出牌阶段限一次，你可以与一名角色拼点。若你：赢，跳过其下个摸牌阶段；没赢：你弃置两张牌。",
  ["@@SP_heg__changshi__yaozhuo"] = "谣诼",
  ["$SP_heg__changshi__yaozhuo1"] = "上蔽天听，下诓朝野！",
}

changshiYaozhuo:addRelatedSkill(changshiYaozhuoDebuff)
hiddenspChangshi:addSkill(changshiYaozhuo)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__yaozhuo")

local changshixiaolu = fk.CreateActiveSkill{
  name = "SP_heg__changshi__xiaolu",
  anim_type = "drawcard",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_num = 0,
  card_num = 0,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    from:drawCards(2, self.name)
    if from.dead or from:isKongcheng() then return end
    local choice = room:askForChoice(from, { "SP_heg__changshi__xiaolu_give", "SP_heg__changshi__xiaolu_discard" }, self.name)
    if choice == "SP_heg__changshi__xiaolu_discard" then
      room:askForDiscard(from, 2, 2, false, self.name, false)
    else
      local all = from:getCardIds("h")
      local to_give = #all > 2 and room:askForCard(from, 2, 2, false, self.name, false, nil, "#SP_heg__changshi__xiaolu-give:::" .. 2) or all
      local tgt = room:askForChoosePlayers(from, table.map(
        room:getOtherPlayers(from), Util.IdMapper), 1, 1, "#SP_heg__changshi__xiaolu-give-choose", self.name, false)[1]

      local tmp = Fk:cloneCard("slash")
      tmp:addSubcards(to_give)
      room:obtainCard(room:getPlayerById(tgt), tmp, false, fk.ReasonGive, from.id)
    end
  end,
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__xiaolu"] = "宵赂",
  [":SP_heg__changshi__xiaolu"] = "出牌阶段限一次，你可以摸两张牌，然后选择一项：1.弃置两张手牌；2.将两张手牌交给一名其他角色。",
  ["SP_heg__changshi__xiaolu_give"] = "交出两张手牌",
  ["SP_heg__changshi__xiaolu_discard"] = "弃置两张手牌",
  ["#SP_heg__changshi__xiaolu-give"] = "宵赂：请选择要交出的 %arg 张牌",
  ["#SP_heg__changshi__xiaolu-give-choose"] = "宵赂：请选择要交给的目标",
  ["$SP_heg__changshi__xiaolu1"] = "咱家上下打点，自是要费些银子。",
}

hiddenspChangshi:addSkill(changshixiaolu)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__xiaolu")

local changshiKuiji = fk.CreateActiveSkill{
  name = "SP_heg__changshi__kuiji",
  anim_type = "control",
  prompt = "#SP_heg__changshi__kuiji-prompt",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 1
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= Self.id and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local player_hands = player:getCardIds("h")
    local target_hands = target:getCardIds("h")
    local cards = room:askForPoxi(player, "SP_heg__changshi__kuiji_discard", {
      { player.general, player_hands },
      { target.general, target_hands },
    }, nil, true)
    if #cards == 0 then return end
    local cards1 = table.filter(cards, function(id) return table.contains(player_hands, id) end)
    local cards2 = table.filter(cards, function(id) return table.contains(target_hands, id) end)
    local moveInfos = {}
    if #cards1 > 0 then
      table.insert(moveInfos, {
        from = player.id,
        ids = cards1,
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonDiscard,
        proposer = effect.from,
        skillName = self.name,
      })
    end
    if #cards2 > 0 then
      table.insert(moveInfos, {
        from = target.id,
        ids = cards2,
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonDiscard,
        proposer = effect.from,
        skillName = self.name,
      })
    end
    room:moveCards(table.unpack(moveInfos))

    return false
  end,
}
Fk:addPoxiMethod{
  name = "SP_heg__changshi__kuiji_discard",
  card_filter = function(to_select, selected, data)
    local suit = Fk:getCardById(to_select).suit
    if suit == Card.NoSuit then return false end
    return not table.find(selected, function(id) return Fk:getCardById(id).suit == suit end)
  end,
  feasible = function(selected)
    return #selected == 4
  end,
  prompt = function ()
    return "#SP_heg__changshi__kuiji-poxi_prompt"
  end
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__kuiji"] = "窥机",
  [":SP_heg__changshi__kuiji"] = "出牌阶段限一次，你可以观看一名其他角色的手牌并可弃置你与其手牌中共计四张花色各不相同的牌。",
  ["SP_heg__changshi__kuiji_discard"] = "窥机观看",
  ["#SP_heg__changshi__kuiji-prompt"] = "窥机：选择一名有手牌的其他角色，并可弃置你与其手牌中共计四张花色各不相同的牌",
  ["#SP_heg__changshi__kuiji-poxi_prompt"] = "窥机：弃置双方手里四张不同花色的牌",
  ["$SP_heg__changshi__kuiji1"] = "同道者为忠，殊途者为奸！",
}

hiddenspChangshi:addSkill(changshiKuiji)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__kuiji")

local changshiChihe = fk.CreateTriggerSkill{
  name = "SP_heg__changshi__chihe",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      data.card.trueName == "slash" and
      #AimGroup:getAllTargets(data.tos) == 1
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cardUseEvent = room.logic:getCurrentEvent().parent
    cardUseEvent.changshiChiheUsed = true

    local cards = room:getNCards(2)
    room:moveCardTo(cards, Card.Processing)

    local idsMatched = table.filter(cards, function(id)
      local c = Fk:getCardById(id)
      return data.card.suit == c.suit
    end)

    room:setPlayerMark(room:getPlayerById(data.to), self.name, table.map(cards, function (id) return Fk:getCardById(id).suit end))
    if #idsMatched > 0 then
      data.additionalDamage = (data.additionalDamage or 0) + #idsMatched
    end

    local cardsInProcessing = table.filter(cards, function(id) return room:getCardArea(id) == Card.Processing end)
    if #cardsInProcessing > 0 then
      room:moveCardTo(cardsInProcessing, Card.DiscardPile)
    end
  end,

  refresh_events = {fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.room.logic:getCurrentEvent().changshiChiheUsed
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room:getAlivePlayers()) do
      room:setPlayerMark(p, self.name, 0)
    end
  end,
}

local changshiChiheProhibit = fk.CreateProhibitSkill{
  name = "#ze_changshiChihe_prohibit",
  prohibit_use = function(self, player, card)
    -- FIXME: 确保是因为【杀】而出闪，并且指明好事件id
    if Fk.currentResponsePattern ~= "jink" or card.name ~= "jink" or player:getMark("SP_heg__changshi__chihe") == 0 then
      return false
    end
    if table.contains(player:getMark("SP_heg__changshi__chihe"), card.suit) then
      return true
    end
  end,
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__chihe"] = "叱吓",
  [":SP_heg__changshi__chihe"] = "出牌阶段限一次，当你使用【杀】指定唯一目标后，你可以亮出牌堆顶两张牌，令其不能使用与亮出的牌花色相同的牌响应此【杀】，"..
  "且其中每有一张牌与此【杀】花色相同，此【杀】伤害基数便+1。",
  ["$SP_heg__changshi__chihe1"] = "想见圣上？哼哼，你怕是没这个福分了！",
}

changshiChihe:addRelatedSkill(changshiChiheProhibit)
hiddenspChangshi:addSkill(changshiChihe)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__chihe")

local changshiNiqu = fk.CreateActiveSkill{
  name = "SP_heg__changshi__niqu",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 1
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    room:damage({
      from = room:getPlayerById(effect.from),
      to = room:getPlayerById(effect.tos[1]),
      damage = 1,
      damageType = fk.FireDamage,
      skillName = self.name
    })

    return false
  end,
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__niqu"] = "逆取",
  [":SP_heg__changshi__niqu"] = "出牌阶段限一次，你可以对一名其他角色造成1点火焰伤害。",
  ["$SP_heg__changshi__niqu1"] = "离心离德，为吾等所不容！",
}

hiddenspChangshi:addSkill(changshiNiqu)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__niqu")

local changshiMiaoyu = fk.CreateViewAsSkill{
  name = "SP_heg__changshi__miaoyu",
  pattern = "peach,slash,jink,nullification",
  card_filter = function(self, to_select, selected)
    if #selected == 2 then
      return false
    elseif #selected == 1 then
      return Fk:getCardById(to_select):compareSuitWith(Fk:getCardById(selected[1]))
    else
      local suit = Fk:getCardById(to_select).suit
      local c
      if suit == Card.Heart then
        c = Fk:cloneCard("peach")
      elseif suit == Card.Diamond then
        c = Fk:cloneCard("fire__slash")
      elseif suit == Card.Club then
        c = Fk:cloneCard("jink")
      elseif suit == Card.Spade then
        c = Fk:cloneCard("nullification")
      else
        return false
      end
      return (Fk.currentResponsePattern == nil and c.skill:canUse(Self, c)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(c))
    end
  end,
  view_as = function(self, cards)
    if #cards == 0 or #cards > 2 then
      return nil
    end
    local suit = Fk:getCardById(cards[1]).suit
    local c
    if suit == Card.Heart then
      c = Fk:cloneCard("peach")
    elseif suit == Card.Diamond then
      c = Fk:cloneCard("fire__slash")
    elseif suit == Card.Club then
      c = Fk:cloneCard("jink")
    elseif suit == Card.Spade then
      c = Fk:cloneCard("nullification")
    else
      return nil
    end
    c.skillName = self.name
    c:addSubcards(cards)
    return c
  end,
  before_use = function(self, player, use)
    local num = #use.card.subcards
    if num == 2 then
      local suit = Fk:getCardById(use.card.subcards[1]).suit
      if suit == Card.Diamond then
        use.additionalDamage = (use.additionalDamage or 0) + 1
      elseif suit == Card.Heart then
        use.additionalRecover = (use.additionalRecover or 0) + 1
      end
    end
  end,
}
local changshiMiaoyuDiscard = fk.CreateTriggerSkill{
  name = "#SP_heg__changshi__miaoyu_discard",
  events = {fk.CardUseFinished},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and table.contains(data.card.skillNames, "SP_heg__changshi__miaoyu") and #data.card.subcards == 2 and
      Fk:getCardById(data.card.subcards[1]).color == Card.Black
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if not room.current:isNude() then
      local cid = room:askForCardChosen(player, room.current, "he", self.name)
      room:throwCard({cid}, self.name, room.current, player)
    end
  end,
}
Fk:loadTranslationTable{
  ["SP_heg__changshi__miaoyu"] = "妙语",
  [":SP_heg__changshi__miaoyu"] = "出牌阶段限一次，你可以将至多两张同花色的牌按以下规则使用或打出：<font color='red'>♥</font>当【桃】，<font color='red'>♦</font>当火【杀】，"..
  "♣当【闪】，♠当【无懈可击】。若你以此法使用或打出了两张：红桃牌，此牌回复基数+1；方块牌，此牌伤害基数+1；黑色牌，你弃置当前回合角色一张牌。",
  ["$SP_heg__changshi__miaoyu1"] = "小伤无碍，安心修养便可。",
}
changshiMiaoyu:addRelatedSkill(changshiMiaoyuDiscard)
hiddenspChangshi:addSkill(changshiMiaoyu)
SP_heg__shichangshi:addRelatedSkill("SP_heg__changshi__miaoyu")
Fk:loadTranslationTable{
  ["@&changshiCards"] = "常侍",
}
for generalName, _  in pairs(tenChangShiMapper) do
  local changshi = General(extension, generalName, "qun", 0)
  changshi.total_hidden = true
end
---@param player ServerPlayer
local addDangguSkill = function(player, skill_name)
  local room = player.room
  local skill = Fk.skills[skill_name]
  if skill == nil or player:hasSkill(skill_name, true) then return false end
  room:handleAddLoseSkills(player, skill_name, nil)
  local pingjian_skills = player:getTableMark( "spchao_skills")
  table.insertIfNeed(pingjian_skills, skill_name)
  room:setPlayerMark(player, "spchao_skills", pingjian_skills)
  local pingjian_skill_times = player:getTableMark( "spchao_skill_times")
  table.insert(pingjian_skill_times, {skill_name, player:usedSkillTimes(skill_name)})
  for _, s in ipairs(skill.related_skills) do
    table.insert(pingjian_skill_times, {s.name, player:usedSkillTimes(s.name)})
  end
  room:setPlayerMark(player, "spchao_skill_times", pingjian_skill_times)
end

---@param player ServerPlayer
local removeDangguSkill = function(player, skill_name)
  local room = player.room
  local skill = Fk.skills[skill_name]
  if skill == nil then return false end
  room:handleAddLoseSkills(player, "-" .. skill_name, nil)
  local pingjian_skills = player:getTableMark( "spchao_skills")
  table.removeOne(pingjian_skills, skill_name)
  room:setPlayerMark(player, "spchao_skills", pingjian_skills)
  local invoked = false
  local pingjian_skill_times = player:getTableMark( "spchao_skill_times")
  local record_copy = {}
  for _, pingjian_record in ipairs(pingjian_skill_times) do
    if #pingjian_record == 2 then
      local record_name = pingjian_record[1]
      if record_name == skill_name or not table.every(skill.related_skills, function (s)
          return s.name ~= record_name end) then
        if player:usedSkillTimes(record_name) > pingjian_record[2] then
          invoked = true
        end
      else
        table.insert(record_copy, pingjian_record)
      end
    end
  end
  room:setPlayerMark(player, "spchao_skill_times", record_copy)
end

local function getPingjianSkills(player, event)
  local list = {
    ["play"] = {
      "SP_heg__changshi__taoluan",
      "SP_heg__changshi__chiyan",
      "SP_heg__changshi__zimou",
      "SP_heg__changshi__picai",
      "SP_heg__changshi__yaozhuo",
      "SP_heg__changshi__xiaolu",
      "SP_heg__changshi__kuiji",
      "SP_heg__changshi__chihe",
      "SP_heg__changshi__niqu",
      "SP_heg__changshi__miaoyu",
    },
  }
  local used_skills = player:getTableMark( "spchao_used_skills")
  return table.filter(list[event] or {}, function (skill_name)
    return Fk.skills[skill_name] and not table.contains(used_skills, skill_name) and not player:hasSkill(skill_name, true)
  end)
end
local spchao = fk.CreateActiveSkill{
  name = "spchao",
  prompt = "#spchao-active",
  card_num = 0,
  target_num = 0,
  can_use = function(self, player)
    return player:getMark("spchao_used-phase") == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    player:drawCards(1, self.name)
    room:setPlayerMark(player, "spchao_used-phase", 1)
    local skills = getPingjianSkills(player, "play")
    if #skills == 0 then return false end
    local choices = table.random(skills, 3)
    local skill_name = room:askForChoice(player, choices, self.name, "#spchao-choice", true)
    local used_skills = player:getTableMark( "spchao_used_skills")
    table.insert(used_skills, skill_name)
    room:setPlayerMark(player, "spchao_used_skills", used_skills)
    local phase_event = room.logic:getCurrentEvent():findParent(GameEvent.Phase)
    if phase_event ~= nil then
      addDangguSkill(player, skill_name)
      phase_event:addCleaner(function()
        removeDangguSkill(player, skill_name)
      end)
    end
  end,
}
local spchao_invalidity = fk.CreateInvaliditySkill {
  name = "#spchao_invalidity",
  invalidity_func = function(self, player, skill)
    local pingjian_skill_times = player:getTableMark("spchao_skill_times")
    return table.find(pingjian_skill_times, function (pingjian_record)
      if #pingjian_record == 2 then
        local skill_name = pingjian_record[1]
        if skill.name == skill_name or not table.every(skill.related_skills, function (s)
          return s.name ~= skill_name end) then
            return player:usedSkillTimes(skill_name) > pingjian_record[2]
        end
      end
    end)
  end
}
spchao:addRelatedSkill(spchao_invalidity)
SP_heg__shichangshi:addSkill(spchao)
Fk:loadTranslationTable{
  ["spchao"] = "党锢",
  ["#spchao_trigger"] = "党锢",
  [":spchao"] = "出牌阶段限一次，你可以摸一张牌然后“结党”（随机抽取三张“常侍”牌，"..
  "选择一张“常侍”牌，你此阶段视为拥有此“常侍”牌的技能，且此阶段结束时移去此“常侍”牌）。",
  ["#spchao-active"] = "“结党”，从两张“常侍”牌中选择一张",
  ["#spchao-choice"] = "“结党”：选择一张“常侍”牌",
}

return extension